package mybatis;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.LambdaUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import mybatis.entity.UserEntity;
import mybatis.mapper.UserMapper;
import org.junit.Test;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.List;

/**
 * @author jackcfan
 * @date 22/9/14
 */
public class MyBatisPlusTest extends BaseTest{

  @Test
  public void test(){
    UserMapper mapper = context.getBean(UserMapper.class);

    /**
     * 手动开启事务
     * 默认情况下 Mapper 每次查询后都会关闭 sqlSession ，从而导致2次相同查询不会走一级缓存
     * 开启事务后，2次查询都是同一个 sqlSession
     * {@link org.mybatis.spring.SqlSessionTemplate} {@link org.mybatis.spring.SqlSessionTemplate.SqlSessionInterceptor}
     * */
    DataSourceTransactionManager txManager = (DataSourceTransactionManager)context.getBean("txManager");
    TransactionStatus transaction = txManager.getTransaction(new DefaultTransactionDefinition());

    /**
     * {@link org.apache.ibatis.binding.MapperProxy}
     * {@link org.mybatis.spring.SqlSessionTemplate.SqlSessionInterceptor} 如果没有开启事务，则自动提交并关闭 sqlSession
     * */
    UserEntity user1 = mapper.queryById(1L);
    UserEntity user2 = mapper.queryById(1L);

    System.out.println(user1 != null && user1 == user2);
  }

  /**
   * SQL 自动注入
   * {@link com.baomidou.mybatisplus.core.injector.ISqlInjector}
   * */
  @Test
  public void sqlInjectorTest(){

  }

  /**
   * lambda 表达式转字段名称
   * {@link com.baomidou.mybatisplus.core.conditions.AbstractLambdaWrapper#columnToString(SFunction)}
   * {@link com.baomidou.mybatisplus.core.conditions.AbstractLambdaWrapper#getColumnCache(SFunction)}
   * {@link LambdaUtils#extract(SFunction)}
   * */
  @Test
  public void lambdaTest(){
    /**
     * Wrappers.lambdaQuery(UserEntity.class)
     * {@link Wrappers#lambdaQuery(Object)}
     * */
    LambdaQueryWrapper<UserEntity> query = new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getId, 1);

    query = Wrappers.lambdaQuery(UserEntity.class).eq(UserEntity::getId, 1);

    List<UserEntity> list = new UserEntity().selectList(query);
    System.out.println(JSON.toJSONString(list, true));
  }

  /**
   * QueryWrapper ,字段名直接使用字符串
   * */
  @Test
  public void query(){
    QueryWrapper<UserEntity> query = new QueryWrapper<UserEntity>().eq("id", 1);

    List<UserEntity> list = new UserEntity().selectList(query);
    System.out.println(JSON.toJSONString(list, true));
  }
}
